package com.hbsi.demo1;

/**
 * @author 程奕红
 * @version 1.0
 */
public class TicketWindow2 implements Runnable {
    private int ticket = 20;

    @Override
    //synchronized也可以加在方法首部，但是如果加在这个方法上，力度就比较大，一个线程就会卖完所有票，就不是多线程并发了
    public void run() {
        int i = 1;
        while (true) {
            synchronized (this) {//同步代码块
                if (ticket > 0) {
                    System.out.println("第" + i + "次卖票" + Thread.currentThread().getName() + "正在发售第" + ticket + "张票");
                    i++;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}